<template>
	<view class="login-box">
		<view class="uni-global-title">
			登录：
		</view>
		<view class="uni-global-label">
			登录易派到家admin后台管理
		</view>
		
		<view class="login-body">
			<u-form :model="form1" ref="form1" class="u-form" label-width="0" v-if="convert" >
				<view class="u-form-textInput">
					<view class="u-form-name">
					</view>
					<u-form-item prop="username" :border-bottom="false">
						<u-input class="u-form-input" v-model="form1.username" @confirm="submit" style="margin:0" placeholder="用户名" />
					</u-form-item>
				</view>
				<view class="u-form-textInput">
					<view class="u-form-name">
					</view>
					<u-form-item prop="password" :border-bottom="false">
						<u-input class="u-form-input" v-model="form1.password" 
							style="margin:0" placeholder="密码" 
							type="password"
							@confirm="submit"
						/>
					</u-form-item>
				</view>
				<view class="convert"  >
					<text @click="couvertForm(false)"  >
						短信验证码登录
					</text>
				</view>
			</u-form>
			<u-form :model="form2" ref="form2" class="u-form" label-width="0" v-else >
				<view class="u-form-textInput">
					<view class="u-form-name">
					</view>
					<u-form-item prop="mobile" :border-bottom="false">
						<u-input class="u-form-input" v-model="form2.mobile" @confirm="submit" style="margin:0" placeholder="手机号" />
					</u-form-item>
				</view>
				<view class="u-form-textInput" v-if="true" >
					<view class="u-form-name">
					</view>
					<u-form-item prop="code" :border-bottom="false">
						<u-input class="u-form-input" v-model="form2.code" 
							style="margin:0" placeholder="验证码" 
						/>
						<text class="login-code" @click="getCode"  >
							{{buttonText}}
						</text>
					</u-form-item>
				</view>
				<view class="convert"  >
					<text @click="couvertForm(true)">
						账号密码登录
					</text>
				</view>
			</u-form>
			<u-button @click="submit" type="success" >
				登录
			</u-button>
		</view>
	</view>
	<u-toast ref="uToast" />
</template>

<script>
	const Admin = uniCloud.importObject("admin",{customUI:true}) ;
	export default {
		data() {
			return {
				convert:false,// 切换验证码或者密码登录
				form1: {
					username: '',
					password:'',
				},
				form2: {
					mobile: '',
					code:'',
				},
				// 验证码倒计时时间，单位为秒
				countdown: 60,
				tempCode: 'asdasd55464646asdas',
				buttonText: '获取验证码',
				rules: {
					username: [{
						required: true,
						message: '请输入用户名',
						trigger: ['change', 'blur']
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: ['change', 'blur']
					}],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['blur']
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change','blur'],
						}
					],
					code:[
						{
							required: true,
							message: '请输入验证码',
							trigger: ['change', 'blur']
						}
					]
				}
			};
		},
		methods:{
			submit(){
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs[this.convert?'form1':'form2'].validate().then(res => {
					// 获取用户信息
					console.log(res)
					if(res) return this.convert? this.loginPassword() : this.loginMobile() ;
				}).catch(errors => {
					this.$refs.uToast.show({
						title: '校验失败',type: 'error',duration:1500,position:'top',
					})
				})
			},
			// 密码登录
			loginPassword(){
				Admin.loginPassword(this.form1).then(result => {
					if(result.code != 200) return this.$refs.uToast.show({title: result.message,type: 'error',duration:1500,position:'top' });
					
					if(result.code == 200){
						this.$store.commit("SET_USER_INFO",{user:result.result})
						this.$refs.uToast.show({title: result.message,type: 'success',duration:1500,position:'top' })
						setTimeout(()=>{ uni.navigateTo({url:result.url} )},800)
					}
				})
			},
			// 手机验证码登录
			loginMobile(){
				console.log('验证码');
				// 检查验证码是否正确
				if (this.tempCode != this.form2.code) {
					uni.showToast({
						title: "验证码错误或已失效",
						icon: "none"
					});
					return;
				}
				Admin.loginMobile(this.form2).then(result => {
					if(result.code != 200) return this.$refs.uToast.show({title: result.message,type: 'error',duration:1500,position:'top' });
					
					if(result.code == 200){
						this.$store.commit("SET_USER_INFO",{user:result.result})
						this.$refs.uToast.show({title: result.message,type: 'success',duration:1500,position:'top' })
						setTimeout(()=>{ uni.navigateTo({url:result.url} )},800)
					}
				})
			},
			// 切换验证码或密码登录
			couvertForm(couvert){
				this.convert = couvert;
				setTimeout(()=>{this.$refs[this.convert?'form1':'form2'].setRules(this.rules);},50)
			},
			/**
			 * 获取验证码*/
			async getCode() {
				if (this.isCountingDown) return; // 如果正在倒计时中，则不执行获取验证码的逻辑
				if (this.form2.mobile.length != 11) return this.$refs.uToast.show({title:'请先填写手机号',type: 'warning',duration:1500,position:'top' });
				let phoneNumberValidator = await Admin.PhoneNumberValidator(this.form2.mobile);
				if(!phoneNumberValidator.data) return  this.$refs.uToast.show({title:phoneNumberValidator.message,type: 'warning',duration:1500,position:'top' });
				this.startCountdown(); // 启动倒计时
				// 模拟发送验证码请求
				this.tempCode = Math.floor(Math.random() * 9000 + 1000); // 生成一个四位数的随机验证码
				// return console.log(this.tempCode);
				// 在这里可以将验证码发送给用户或根据需求进行后续操作
				Admin.sendSms(this.form2.mobile, this.tempCode).then(res => {
					if (res.success) {
						this.$refs.uToast.show({title:'发送成功',type: 'success',duration:1500,position:'top' });
					}
				}).catch(error => {
					console.log(error);
					this.$refs.uToast.show({title:'发送失败',type: 'warning',duration:1500,position:'top' });
				})
				
			},
			startCountdown() {
				this.isCountingDown = true;
				this.buttonText = `${this.countdown}秒后重试`;
				const timer = setInterval(() => {
					this.countdown--;
					if (this.countdown <= 0) {
						clearInterval(timer);
						this.resetCountdown();
					} else {
						this.buttonText = `${this.countdown}秒后重试`;
					}
				}, 1000);
			},
			resetCountdown() {
				this.isCountingDown = false;
				this.countdown = 60;
				this.buttonText = '获取验证码';
			},
		},
		onReady() {
			this.$refs[this.convert?'form1':'form2'].setRules(this.rules);
		}
	}
</script>

<style lang="scss">
	.convert{
		color:#2980b9;
		cursor: pointer;
		padding-bottom:8px;
	}
	.login-body{
		.login-code{
			cursor: pointer;
			color:$uni-color-primary;
		}
	}
	.login-box{
		width: 400px;
		padding:30px;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%); /* 居中 */
		background-color: rgba(255, 255, 255, 0.6);
		backdrop-filter: blur(6px);
		-webkit-backdrop-filter: blur(6px);
		border: 0.8px solid rgba(255, 255, 255, 0.18);
		box-shadow: rgba(142, 142, 142, 0.19) 0px 6px 15px 0px;
		-webkit-box-shadow: rgba(142, 142, 142, 0.19) 0px 6px 15px 0px;
		border-radius: 18px;
		-webkit-border-radius: 18px;
	}
</style>
<style>
	page{
		width: 100%;
		height: 100%;
		position: relative;
		background-image: url('https://mp-81905721-8ef4-452d-a933-876d5a6afc67.cdn.bspapp.com/images/83b85a3ec78c334f7c9fe4a3e38d897d99e9489f4b6a17-CaGgpW.png');
		 background-repeat: no-repeat;
		
		      background-position: center;
		
		      background-size: cover;
	}
</style>
